package com.wx.tgp.socket.demo.thread;

import org.apache.log4j.Logger;

import javax.xml.bind.DatatypeConverter;
import java.io.FileInputStream;
import java.security.DigestInputStream;
import java.security.MessageDigest;

/**
 * 计算一个256位的散列算法信息，利用的是DigestInputStream流来读取数据，
 * 并在digest对象是获取到散列数据
 */
public class DigestThread extends Thread{
    Logger log =  Logger.getLogger(DigestThread.class);
    private String fileName;

    public DigestThread(String fileName){
        this.fileName=fileName;
    }

    public void run(){
        try{
            FileInputStream fis = new FileInputStream(fileName);
            MessageDigest md = MessageDigest.getInstance("SHA-256");
            DigestInputStream dis = new DigestInputStream(fis,md);
            while(dis.read()!=-1){
//                System.out.println(dis.read());
                log.info(dis.read());
            };
            dis.close();
            byte[] digest = md.digest();
            StringBuffer result = new StringBuffer(fileName);
            result.append("：");
            result.append(DatatypeConverter.printHexBinary(digest));
            log.info(result);
//            System.out.println(result);
        }catch (Exception e){
            e.printStackTrace();
        }
    }

    public static void main(String[] args){
        String str = "d://清单.txt";
        Thread t = new DigestThread(str);
        t.start();
    }
}
